function collectFormData(fields) {
	var data = {};
	for (var i = 0; i < fields.length; i++) {
		var $item = $(fields[i]);
		data[$item.attr('name')] = $item.val();
	}
	return data;
}

function processAddEditForm(addEditValidationUrl, performAddEditUrl) {
	$(document).ready(function() {
		var $form = $('#add-edit-form');
		$form.bind('submit', function(e) {
			// AJAX validation
			var $formElements = $form.find('input[type!=radio], select, textarea');
			var formElementsData = collectFormData($formElements);
			formElementsData["type"] = $('input[name=type]:radio:checked').val();
			$.post(addEditValidationUrl, formElementsData, function(response) {
				$form.find('.help-inline').empty();
				if (response.status == 'FAILURE') {
					for (var i = 0; i < response.errorMessageList.length; i++) {
						var item = response.errorMessageList[i];
						var $controlGroup = $('#' + item.fieldName + "ControlGroup");
						$controlGroup.find('.help-inline').html(item.message);
					}
				} else {
					performAddEdit(performAddEditUrl, formElementsData, $form);
				}
			}, 'json');
			e.preventDefault();
			return false;
		});
	});
}

function performAddEdit(performAddEditUrl, parameters, $form) {
	$(document).ready(function() {
	    $.ajax({
	        type: 'POST',
	        url:  performAddEditUrl,
	        data: parameters,
	        dataType: 'json',
	        async: true,
	        success: function(result) {
	        	if (result.status == 'SUCCESS') {
	        		$form.unbind('submit');
					$form.submit();
	        	}
	        	else {
	        		displayGenericErrorNotification();
	        	}
	        },
	        error: function(jqXHR, textStatus, errorThrown) {
	        	displayGenericErrorNotification();
	        }
	    });
	});
}
